<?php

namespace App\Services\CancelProductOrder;

use App\Models\Order;
use App\Models\Reward;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class CancelProductOrder
{
	protected $order;
	protected $money;
	
	public function __construct(Order $order,$money)
	{
		$this->order = $order;
		$this->money = $money;
	}
	
	protected function createRefund()
	{
		$order = $this->order;
		
		if($order->refunds()->first()){
			$refund = $order->refunds()->first();
			$refund->update(['refund_status'=>'confirmed','refund_money' => $this->money,]);
			return $refund;
		}else{

			return $order->user->orderRefunds()->create([
				'order_id' => $order->id,
				'type' => 'return_money_only',
				'reason' => 'other_problem',
				'refund_money' => $this->money,
				'parcel_status' => 'unreceived',
				'refund_status' => 'confirmed',
				'is_order_cancel' => true,
			]);
		}
		
	}
	
	public function cancel()
	{
		DB::transaction(function () {
			$refund = $this->createRefund();
			$this->order->update(["closed_at"=>Carbon::now(),'cancelled_at'=>Carbon::now()]);
			if($this->order->paid_method != "" && $this->order->paid_method !='free'){
				
				cashier($this->order->paid_method)->refundOrder($this->order);

			}


			$rewards = Reward::query()->where('order_id',$this->order->id)->get();
			if($rewards){


				foreach($rewards as $reward){
					
					if($reward->remark =="own_order"){
						 account_rewards($reward->user)->minusOrderRefundRewardsByOwn($reward->money);

					}elseif($reward->remark =="first_level"){
						 account_rewards($reward->user)->minusOrderRefundRewards($reward->money,1,$reward->children->name);
					}else{

						 account_rewards($reward->user)->minusOrderRefundRewardsSecond($reward->money,2,$reward->children->name);
					}

				}
			}

			
		});
	}
}
